<template>
  <div class="main-container">
    <!-- 面包屑 -->
    <div class="breadcrumb">
      <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item>工艺路线管理</el-breadcrumb-item>
        <el-breadcrumb-item>产品工艺库</el-breadcrumb-item>
        <el-breadcrumb-item>{{ this.title }}</el-breadcrumb-item>
      </el-breadcrumb>
    </div>

    <!-- 新建/修改工艺版本 -->
    <div class="add-procee-pane">
      <!-- 版本/产品信息 -->
      <el-row class="text-center">
        <el-col :span="6">
          <h3>工艺版本：{{ basics.versionName }}</h3>
        </el-col>
        <el-col :span="6">
          <h3>图号：{{ basics.drawingNumber }}</h3>
        </el-col>
        <el-col :span="6">
          <h3>品名：{{ basics.productName }}</h3>
        </el-col>
        <el-col :span="6">
          <h3>材质：{{ basics.materialQuality }}</h3>
        </el-col>
      </el-row>

      <!-- 工艺路线 -->

      <!-- 工序编辑区域 -->
      <!-- <div v-if="canEdit">
          <el-row class="mt0">
            <el-form-item class="w-100percent bold bg-lightGray mb5">
              <span>工序录入&nbsp;&nbsp;&nbsp;&nbsp;</span>
              <el-button id="btnC9Add" v-if="!isEditProcess" @click="addProcess()" type="text" icon="el-icon-plus" size="small">添加工序&nbsp;&nbsp;&nbsp;&nbsp;</el-button>
              <el-button id="btnC9Finish" v-if="!isEditProcess" @click="addFinishProcess()" type="text" icon="el-icon-plus" size="small">整备与完工</el-button>
              <el-button id="btnC9Confirm" v-if="isEditProcess" @click="confirmProcess" type="text" icon="el-icon-check" size="small" class="color-hdbl">确认工序&nbsp;&nbsp;&nbsp;&nbsp;</el-button>
              <el-button id="btnC9CancelConfirm" v-if="isEditProcess" @click="cancelEditProcess" type="text" icon="el-icon-close" size="small" class="color-hdbl">取消编辑</el-button>
            </el-form-item>
          </el-row>
          <el-row class="mb10" v-if="isEditProcess">
            <el-col :span="3">
              <el-form-item class="mb0" prop="sequenceNumber" label="工序号">
                <el-input-number v-model="tempProcess.sequenceNumber" size="small" class="w100" :min="1" :max="this.processList.length + 1"></el-input-number>
              </el-form-item>
            </el-col>
            <el-col :span="4">
              <el-form-item class="mb0" prop="processName" label="工序名称">
                <el-autocomplete
                  id="iptC9ProcessName"
                  class="w150"
                  v-model="tempProcess.processName"
                  :fetch-suggestions="querySearch"
                  placeholder="请输入内容"
                  @select="handleSelect"
                ></el-autocomplete>
              </el-form-item>
            </el-col>
            <el-col :span="4">
              <el-form-item v-if="tempProcess.processName != '完工'" class="mb0" prop="department" label="部门/执行">
                <el-select id="selectC9Department" class="w150" v-model="tempProcess.department" filterable @change="onChangeDepartment">
                  <template v-for="option in options">
                    <el-option :id="'optionC9Department' + option" :key="option" :label="option" :value="option"></el-option>
                  </template>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col v-if="tempProcess.department == '加工'" :span="6">
              <el-switch v-model="tempProcess.single" active-text="单机" inactive-text="双机" active-color="#004098" @change="changeMul" class="mt10"></el-switch>
            </el-col>
          </el-row>
          <div v-if="tempProcess.department == '加工' && isEditProcess" class="mb10">
            <el-form-item class="w-100percent mb0"> 设备工时 </el-form-item>
            <hr style="margin-block-start: 0em" />
            <template v-for="(item, eIndex) in tempProcess.equipmentList">
              <el-row :key="eIndex">
                <el-col :span="6">
                  <el-form-item class="no-margin" label="设备名称">
                    <el-select id="selectC9Equipment" class="w275" v-model="item.equipment" clearable :multiple-limit="maxEquitment" multiple filterable placeholder="请选择设备名称">
                      <template v-for="(option, oIndex) in equipmentList">
                        <el-option :id="'optionC9Equipment' + option" :key="oIndex" :label="option" :value="option"></el-option>
                      </template>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="3">
                  <el-form-item class="no-margin" label="调试工时" :prop="'equipmentList.' + eIndex + '.debugHour'" :rules="rules.debugHour">
                    <el-input id="iptC9DebugHour" class="w80" v-model="item.debugHour"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="3">
                  <el-form-item class="no-margin" label="定额工时" :prop="'equipmentList.' + eIndex + '.quotaHour'" :rules="rules.quotaHour">
                    <el-input id="iptC9QuotaHour" class="w80" v-model="item.quotaHour"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="5">
                  <el-form-item>
                    <el-button id="btnC9AddEquipment" @click="addEquit()" type="text" icon="el-icon-plus" size="small" v-if="equitListLen - 1 == eIndex">添加设备</el-button>
                    <el-button @click="deleteEquit(eIndex)" type="text" icon="el-icon-delete" size="small">移除该设备</el-button>
                  </el-form-item>
                </el-col>
              </el-row>
            </template>
          </div>
        </div> -->
      <!-- 工艺路线表格 -->
      <el-form>
        <el-form-item class="w-100percent bold bg-lightGray mb5 mt20">
          工艺路线&nbsp;&nbsp;&nbsp;&nbsp;
          <el-button id="btnC9Finish" v-if="canEdit" @click="addFinishProcess()" type="text" icon="el-icon-plus" size="small">整备与完工</el-button>
        </el-form-item>
        <!-- 编辑视图 -->
        <div>
          <el-table class="mt0 route-table" border stripe :data="processList" v-if="canEdit">
            <!-- Col 1 序号 -->
            <el-table-column prop="sequenceNumber" label="序号" align="center" width="80"></el-table-column>
            <!-- Col 2 工序名称 -->
            <el-table-column prop="processName" label="工序名称" align="left" min-width="100">
              <template slot-scope="scope">
                <el-autocomplete v-model="scope.row.processName" :fetch-suggestions="querySearch" placeholder="请输入内容" @select="handleSelect"></el-autocomplete>
              </template>
            </el-table-column>
            <!-- Col 3 部门 -->
            <el-table-column prop="department" label="部门" align="left" min-width="100">
              <template slot-scope="scope">
                <el-select v-if="scope.row.processName != '完工'" v-model="scope.row.department" filterable @change="onChangeDepartment">
                  <template v-for="option in options">
                    <el-option :key="option" :label="option" :value="option"></el-option>
                  </template>
                </el-select>
              </template>
            </el-table-column>
            <!-- Col 4 单双机 -->
            <el-table-column prop="single" label="单双机" align="center" min-width="80">
              <template slot-scope="scope" v-if="scope.row.department == '加工'">
                <el-switch style="display: block" v-model="scope.row.single" active-color="#13ce66" inactive-color="#ff4949" active-text="单" inactive-text="双"> </el-switch>
              </template>
            </el-table-column>
            <!-- Col 5 调试工时 -->
            <el-table-column prop="debugHour" label="调试工时" align="left" min-width="100">
              <template slot-scope="scope" v-if="scope.row.department == '加工'">
                <el-input v-model="scope.row.debugHour" placeholder="调试工时"></el-input>
              </template>
            </el-table-column>
            <!-- Col 6 定额工时 -->
            <el-table-column prop="quotaHour" label="定额工时" align="left" min-width="100">
              <template slot-scope="scope" v-if="scope.row.department == '加工'">
                <el-input v-model="scope.row.quotaHour" placeholder="定额工时"></el-input>
              </template>
            </el-table-column>
            <!-- Col 7 操作 -->
            <el-table-column label="操作" align="center" fixed="right" min-width="180">
              <template slot-scope="scope" v-if="canEdit && scope.row.sequenceNumber && $checkAuth('修改工艺路线')">
                <el-button type="primary" size="mini" @click="insertProcess(scope.row.sequenceNumber, true)">添加-前</el-button>
                <el-button type="primary" size="mini" @click="insertProcess(scope.row.sequenceNumber, false)">添加-后</el-button>
                <el-button type="danger" size="mini" @click="delProcess(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <!-- 显示视图 -->
        <div>
          <el-table class="mt0 route-table" border stripe :data="processList" v-if="!canEdit">
            <el-table-column prop="sequenceNumber" label="序号" align="center" width="80"></el-table-column>
            <el-table-column prop="processName" label="工序名称" align="center" min-width="100"></el-table-column>
            <el-table-column prop="department" label="部门" align="center" min-width="100"></el-table-column>
            <el-table-column prop="single" label="单双机" align="center" min-width="80">
              <template slot-scope="scope" v-if="scope.row.department == '加工'">
                <div>{{ scope.row.single ? '单机' : '双机' }}</div>
              </template>
            </el-table-column>
            <el-table-column prop="debugHour" label="调试工时" align="center" min-width="100"></el-table-column>
            <el-table-column prop="quotaHour" label="定额工时" align="center" min-width="100"></el-table-column>
            <el-table-column label="操作" align="center" fixed="right" min-width="180"> </el-table-column>
          </el-table>
        </div>
        <el-form-item class="w-100percent bold bg-lightGray mb5 mt20">备注</el-form-item>
        <el-input :readonly="!canEdit" v-model="basics.remark" type="textarea" :rows="3"> {{ basics.remark }} </el-input>
      </el-form>
      <br /><br />
      <el-button v-if="!canEdit && $checkAuth('修改工艺路线')" id="btnC9Edit" type="primary" @click="edit">修改</el-button>
      <el-button v-if="canEdit" id="btnC9Save" type="primary" @click="save">保存</el-button>
      <el-button v-if="canEdit" id="btnC9Copy" type="primary" @click="copy">保存为新版本</el-button>
      <el-button v-if="canEdit" id="btnC9Cancel" @click="cancel">取消</el-button>
      <el-button v-if="!canEdit" type="danger" @click="delProcessVersion">删除</el-button>
      <el-button v-if="!canEdit" id="btnC9Back" @click="close">返回</el-button>
      <el-button v-if="!canEdit" id="btnC9Back" @click="copyToAnother">应用到其他产品</el-button>
      <el-dialog width="400px" title="工艺路线应用" @close="copyRouteDialogClose" :visible="copyRouteVisible">
        <el-form :model="copyRouteForm" :rules="copyRouteRules" label-width="100px">
          <el-form-item label="版本名称" prop="versionName">
            <el-input id="iptC8VersionName" v-model="copyRouteForm.versionName" placeholder="输入版本名称" class="w200"></el-input>
          </el-form-item>
          <el-form-item label="图号" prop="drawingNumber">
            <el-input id="iptC8DrawingNumber" v-model="copyRouteForm.drawingNumber" placeholder="输入图号" class="w200"></el-input>
          </el-form-item>
          <el-form-item label="备注" prop="remark">
            <el-input id="iptC8Remark" type="textarea" v-model="copyRouteForm.remark" placeholder="输入备注" class="w200"></el-input>
          </el-form-item>
        </el-form>
        <el-button id="btnC8Next" type="primary" @click="coppRouteToAnother">确定</el-button>
        <el-button id="btnC8Cancel" @click="copyRouteDialogClose">取消</el-button>
      </el-dialog>
    </div>
  </div>
</template>

<script lang="ts">
import { Vue, Component } from 'vue-property-decorator'
import { namespace } from 'vuex-class'
import AddProduct from '../process/addProduct.vue'
import _ from 'lodash'

const vuexProcess = namespace('TwoProcess')

@Component({
  components: {
    AddProduct
  }
})
export default class EditProcessDetail extends Vue {
  insertProcess(sequenceNumber, dir) {
    let newProcessIndex = Number(sequenceNumber)
    if (dir) newProcessIndex -= 1
    let process = {
      sequenceNumber: newProcessIndex,
      processName: '',
      department: '',
      single: true,
      debugHour: 0.0,
      quotaHour: 0.0
    }
    this.processList.splice(newProcessIndex, 0, process)
    // 重新对工序列表进行sequenceNumber和sid的绑定
    this.sequencingProcess()
  }

  tableRowClassName({ row, rowIndex }) {
    if (row.department === '采购' || row.department === '外协') {
      return 'row-outsource-process'
    } else if (row.processName === '完工') {
      return 'row-finish-process'
    } else if (row.debugHour === 0 && row.quotaHour === 0) {
      return 'row-nohour-process'
    }
    return 'row-work-process'
  }

  @vuexProcess.Action PREDATA_VERSION: any

  @vuexProcess.State productOnDesignVersion: any
  @vuexProcess.State productOnModifyVersion: any
  @vuexProcess.State addId: any
  @vuexProcess.State addProduct: any
  @vuexProcess.Mutation setAddId: any
  @vuexProcess.Action CREAT_VERSION: any

  basics: any = {
    drawingNumber: '',
    versionName: '',
    productName: '',
    materialQuality: '',
    remark: ''
  }

  canEdit: boolean = false
  readOnly: boolean = true
  addRemark: boolean = false
  copyRouteVisible: boolean = false
  copyRouteForm: any = {
    drawingNumber: '',
    versionName: '',
    remark: ''
  }
  // 工序编辑区域表单绑定临时数据
  tempProcess: any = {
    sid: '',
    sequenceNumber: 0,
    processName: '',
    department: '',
    single: false,
    equipmentList: [
      {
        sid: '',
        id: 3,
        equipment: '',
        debugHour: '',
        quotaHour: ''
      }
    ]
  }
  // 修改工序过程中 保留原数据 修改完成清空
  editOriginalProcess: any = {}
  // 是否修改原工序
  isEditOriginalProcess: boolean = false

  edit() {
    this.canEdit = true
    this.addRemark = true
    this.addFirstProcess()
  }

  cancel() {
    this.preUpdate()
    this.canEdit = false
  }

  addFirstProcess(){
    if(this.processList.length == 0) {
      let process = {
      sequenceNumber: 1,
      processName: '',
      department: '',
      single: true,
      debugHour: 0.0,
      quotaHour: 0.0
    }
    this.processList.push(process);
    }
  }

  /**
   * 生命周期函数
   */
  created() {
    // 判断入口：新建 or 修改
    let inType = this.$route.params.inType
    if (inType == '1') {
      // 新增工艺版本进入
      this.title = '新建工艺路线'
      this.canEdit = true
      // 绑定产品信息
      this.basics.drawingNumber = this.productOnDesignVersion.drawingNumber
      this.basics.productName = this.productOnDesignVersion.productName
      this.basics.materialQuality = this.productOnDesignVersion.materialQuality
      this.basics.versionName = this.$route.params.versionName
      this.basics.remark = this.$route.params.remark
      this.versionId = this.addId
      this.addFirstProcess()
    } else if (inType == '2') {
      // 修改工艺版本进入
      this.title = '修改工艺路线'
      this.canEdit = true
      // 绑定产品信息
      this.basics.drawingNumber = this.productOnModifyVersion.drawingNumber
      this.basics.productName = this.productOnModifyVersion.productName
      this.basics.materialQuality = this.productOnModifyVersion.materialQuality
      this.basics.versionName = this.productOnModifyVersion.versionName
      this.versionId = this.productOnModifyVersion.versionId
      this.basics.remark = this.productOnModifyVersion.remark
      this.preUpdate()
    } else {
      // 查看工艺版本
      this.title = '查看工艺路线'

      // 绑定产品信息
      this.basics.drawingNumber = this.productOnModifyVersion.drawingNumber
      this.basics.productName = this.productOnModifyVersion.productName
      this.basics.materialQuality = this.productOnModifyVersion.materialQuality
      this.basics.versionName = this.productOnModifyVersion.versionName
      this.versionId = this.productOnModifyVersion.versionId

      this.basics.remark = this.productOnModifyVersion.remark
      console.log(this.basics.drawingNumber)
      console.log(this.basics.remark)

      this.preUpdate()
    }
    // 获取基础数据集
    this.preCreate()
  }

  async preCreate() {
    await this.PREDATA_VERSION()
  }

  /**
   * 保存为新版本
   */
  copy() {
    console.log('=== Log 保存为新版本!!!')
    if (this.validateSubmitProcessList()) {
      this.$prompt('请输入新的版本号', '新建工艺路线：图号' + this.basics.drawingNumber, {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then((value: any) => {
          console.log('点击了确定')
          console.log(value)
          console.log(value.value)
          console.log(String(value.value))
          if (String(value.value) == 'null') {
            this.$alert('版本号不能为空')
          } else {
            let param = {
              drawingNumber: this.basics.drawingNumber,
              versionName: String(value.value)
            }
            this.createNewVersion(param)
          }
        })
        .catch(() => {
          console.log('点击了取消')
        })
    }
  }

  private async createNewVersion(params) {
    this.setAddId(0)
    await this.CREAT_VERSION(params)
    if (this.addId != 0) {
      this.basics.versionName = params.versionName
      this.versionId = this.addId
      this.save()
    }
  }

  /**
   * 应用到其他产品
   */
  copyToAnother() {
    this.copyRouteVisible = true
  }
  coppRouteToAnother() {
    let param = {
      drawingNumber: this.copyRouteForm.drawingNumber,
      versionName: this.copyRouteForm.versionName,
      remark: this.copyRouteForm.remark
    }
    this.createNewVersion(param)
  }

  copyRouteDialogClose() {
    console.log('弹框关闭 === 1')
    this.copyRouteVisible = false
    console.log('弹框关闭 === 2')
  }

  // 对提交的工序列表进行校验
  private validateSubmitProcessList() {
    this.changeData()

    // 判断最后两道工序是整备和完工
    // 工艺路线至少包括两条工序
    // 加工工序需要选择设备
    // 调试工时如果没填默认设置为0
    console.log('提交的工序列表：')
    console.log(this.requestList)
    let length = this.requestList.length

    if (length < 2) {
      this.$alert('工艺路线应该以【整备】和【完工】结束', '错误提示')
      return false
    } else {
      for (let i = 0; i < this.requestList.length; i++) {
        if (this.requestList[i].processName.length == 0) {
          this.$alert('工序' + (i + 1) + '不能为空', '错误提示')
          return false
        }
        if (this.requestList[i].department == '加工') {
          if (!/^[0-9]+([.][0-9]{1,2})?$/.test(this.requestList[i].debugHour)) {
            if (this.requestList[i].debugHour == '') {
              this.requestList[i].debugHour = 0
              this.processList[i].debugHour = 0
            } else {
              this.$alert('工序' + (i + 1) + '调试工时请输入整数或1到2位小数', '错误提示')
              return false
            }
          }
          if (!/^[0-9]+([.][0-9]{1,2})?$/.test(this.requestList[i].quotaHour)) {
            if (this.requestList[i].quotaHour == '') {
              this.requestList[i].quotaHour = 0
              this.processList[i].quotaHour = 0
            } else {
              this.$alert('工序' + (i + 1) + '定额工时请输入整数或1到2位小数', '错误提示')
              return false
            }
          }
        }
      }

      let processFinish = this.requestList[length - 1]
      let processAssemblng = this.requestList[length - 2]
      console.log(processFinish)
      console.log(processAssemblng)

      if (processAssemblng.processName != '整备' || processFinish.processName != '完工') {
        this.$alert('工艺路线应该以【整备】和【完工】结束', '错误提示')
      } else {
        return true
      }
    }
  }

  /**
   * 添加工序
   */
  addProcess() {
    // 显示工序编辑区域
    this.isEditProcess = true
    this.isEditOriginalProcess = false
    const newProcess = {
      sid: '',
      sequenceNumber: '1',
      processName: '',
      department: '',
      equipmentList: [],
      single: true
    }
    let index = (this.curEditIndex = this.processList.length)
    newProcess.sid = 'process' + index
    newProcess.sequenceNumber = (index + 1).toString()
    this.tempProcess = newProcess
  }

  /**
   * 取消编辑工序
   */
  cancelEditProcess() {
    this.tempProcess = {}
    this.isEditProcess = false
  }

  /**
   * 编辑已有工序
   */
  editProcess(row, index) {
    // 修改工艺路线原有工序
    this.isEditOriginalProcess = true
    // 保留原有工序副本
    this.editOriginalProcess = row

    this.curEditIndex = index - 1
    this.maxEquitment = row.single ? 1 : 2
    this.tempProcess = _.cloneDeep(row)
    this.transformEquitToArr()
    this.isEditProcess = true
  }

  /**
   * TODO 确认工序 重复的行ID问题
   */
  confirmProcess() {
    let flag = this.transformEquitToStr()
    if (flag) {
      console.log('=== 保存工序的工序号：' + this.tempProcess.sequenceNumber)
      console.log('=== 是否修改or新建：' + this.isEditOriginalProcess)
      console.log('=== 修改的副本：')
      console.log(this.editOriginalProcess)
      console.log(this.isEditOriginalProcess && this.tempProcess.sequenceNumber == this.editOriginalProcess.sequenceNumber)
      // 修改原有工序 删除工序列表中该工序
      if (this.isEditOriginalProcess) {
        let oldProcessIndex = Number(this.editOriginalProcess.sequenceNumber) - 1
        this.processList.splice(oldProcessIndex, 1)
      }
      // 将编辑后的工序插入工序列表相应位置
      let newProcessIndex = Number(this.tempProcess.sequenceNumber) - 1
      this.processList.splice(newProcessIndex, 0, this.tempProcess)
      // 重新对工序列表进行sequenceNumber和sid的绑定
      this.sequencingProcess()
      // 将一些变量回归初始状态
      this.isEditOriginalProcess = false
      this.editOriginalProcess = {}
      this.isEditProcess = false
    }
  }

  private sequencingProcess() {
    for (let i = 0; i < this.processList.length; i++) {
      this.processList[i].sid = 'process' + i
      this.processList[i].sequenceNumber = i + 1
    }
  }

  /**
   * 设备单双机数量判断
   * 双机设备数组序列化
   */
  private transformEquitToStr() {
    let flag = true
    this.tempProcess.equipmentList = this.tempProcess.equipmentList.map(item => {
      if (this.tempProcess.department == '加工') {
        if (this.tempProcess.single && item.equipment.length != 1) {
          this.$message.warning('单机工序只能选择一台设备')
          flag = false
        } else if (!this.tempProcess.single && item.equipment.length != this.mulNumber) {
          this.$message.warning('双机工序只能选择两台设备')
          flag = false
        } else {
          item.equipment = item.equipment.join(',')
        }
      } else {
        item.equipment = item.equipment.join(',')
      }
      return item
    })
    return flag
  }

  /**
   * 删除工艺版本
   */
  delProcessVersion(process) {
    this.$alert('您确定删除该工艺路线？', '错误提示', {
      confirmButtonText: '确定',
      type: 'error',
      callback: action => {
        if (action === 'confirm') {
          this.$confirm('此操作将永久删除该数据, 是否继续?', '操作提示', {
            cancelButtonText: '取消',
            confirmButtonText: '确定',
            type: 'warning'
          })
            .then(() => {
              this.deleteSix(this.versionId)
            })
            .catch(() => {
              this.$message({
                type: 'info',
                message: '已取消删除'
              })
            })
        }
      }
    })
  }
  @vuexProcess.Action DELETE_VERSION: any
  async deleteSix(versionId) {
    let result = await this.DELETE_VERSION({ versionId: versionId })
    if (result) {
      this.close()
    }
  }
  /************************************************************* */
  public $refs!: {
    form: any
    multipleTable: any
    addproduct: any
  }

  validateWorkHour: any = (rule, value, callback) => {
    let partten = /^([0-9]*)+(\.[0-9]{1,2})?$/
    console.log(value)
    console.log(rule)

    if (!partten.test(value)) {
      callback(new Error('正确格式：0-2位小数'))
    } else {
      callback()
    }
  }

  rules: any = {
    quotaHour: [{ required: true, trigger: 'change', validator: this.validateWorkHour }],
    debugHour: [{ required: false, trigger: 'change', validator: this.validateWorkHour }]
  }

  copyRouteRules: any = {
    versionName: [{ required: true, message: '请填写版本名称', trigger: 'blur' }],
    drawingNumber: [{ required: true, message: '请填写图号', trigger: 'blur' }]
  }

  @vuexProcess.State sixSearch: any
  // @vuexProcess.State addId: any
  @vuexProcess.State addName: any
  @vuexProcess.State supplierList: any
  //supplierList: any[] = ['gongyings1', 'gonggsad2', 'gjerf']
  @vuexProcess.State equipmentList: any
  //equipmentList: any[] = ['sheb', 'shbhjk', 'safghwe']
  @vuexProcess.State processNameList: any
  //processNameList: any[] = ['ghj', 'g', 'gh', 'fg', '完工', '清整']
  @vuexProcess.State processDetailList: any

  // @vuexProcess.Action  PREEDIT_VERSION: any
  @vuexProcess.Action GET_VERSION: any
  // @vuexProcess.Action PREDATA_VERSION: any;
  @vuexProcess.Action updata_VERSION: any
  @vuexProcess.Action GET_PROCESS_DATEBASE: any

  versionId: string = ''
  title: string = '新增工艺版本'
  dialogVisible: boolean = false
  //整体外协
  over: boolean = true

  //删除使用标识
  sid: string = ''
  //key sid
  id: number = 20
  //设备多选
  maxEquitment: number = 1
  //提交的表单数组
  requestList: any[] = []
  // DEquit: boolean = true;
  //输入内容

  formDetail: any = {
    nn: false
  }

  processList: any[] = [
    // {
    //   sid: 1,
    //   sequenceNumber: "1",
    //   processName: "",
    //   department: "",
    //   supplier: "",
    //   single: true,
    //   equipmentList: [],
    // },
  ]
  mulNumber: number = 2 // 双机可选的设备数
  options: any[] = ['采购', '加工', '外协']
  isEditProcess: boolean = false
  curEditIndex: any = 0 // 当前被编辑/添加的工序的Index

  /**
   * 自动填充整备与完工工序
   */
  addFinishProcess() {
    let assembling = {
      sid: '',
      sequenceNumber: 1,
      processName: '整备',
      department: '加工',
      single: true,
      debugHour: 0.0,
      quotaHour: 0.0
    }
    let assemblingIndex = (this.curEditIndex = this.processList.length)
    assembling.sid = 'process' + assemblingIndex
    assembling.sequenceNumber = assemblingIndex + 1
    this.processList.splice(this.curEditIndex, 1, assembling)

    let finish = {
      sid: '',
      sequenceNumber: 1,
      processName: '完工',
      department: '',
      single: true
    }
    let finishIndex = (this.curEditIndex = this.processList.length)
    finish.sid = 'process' + finishIndex
    finish.sequenceNumber = finishIndex + 1
    this.processList.splice(this.curEditIndex, 1, finish)
  }
  addEquit() {
    const add = {
      sid: '',
      equipment: [],
      debugHour: '',
      quotaHour: ''
    }
    //需要全局变量
    add.sid = 'b' + this.curEditIndex + this.tempProcess.equipmentList.length
    this.tempProcess.equipmentList.push(add)
  }
  //删除设备新函数 0714
  deleteEquit(eIndex) {
    this.tempProcess.equipmentList.splice(eIndex, 1)
    this.tempProcess.equipmentList = this.tempProcess.equipmentList.map((item, index) => {
      item.sid = 'b' + this.curEditIndex + index
      return item
    })
  }

  //数组去重
  newArr(arr) {
    for (var i = 0; i < arr.length; i++) {
      for (var j = i + 1; j < arr.length; j++) {
        if (arr[i] == arr[j]) {
          //如果第一个等于第二个，splice方法删除第二个
          arr.splice(j, 1)
          j--
        }
      }
    }
    return arr
  }

  processNameChange(process) {
    if (process == '完工') {
      this.tempProcess.equipmentList = []
      this.tempProcess.department = ''
    }
  }
  handleSelect(item) {
    console.log('选择or输入的工序' + item)
  }

  /**
   * 工序输入框输入提示
   * 注意返回建议列表的数据格式
   * 需要是：{ value:"value" }
   */
  querySearch(queryString, cb) {
    let tempObjArray: any = []
    for (const iterator of this.processNameList) {
      let tempObj = {
        value: iterator
      }
      tempObjArray.push(tempObj)
    }
    var processList = tempObjArray
    var results = queryString ? processList.filter(this.createFilter(queryString)) : processList
    // 调用 callback 返回建议列表的数据
    cb(results)
  }
  createFilter(queryString: string) {
    return restaurant => {
      return restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0
    }
  }
  //更换 设备/供应商的选择列表
  onChangeDepartment(tempProcess) {
    if (tempProcess == '加工' && this.tempProcess.equipmentList.length == 0) {
      this.tempProcess.equipmentList = [
        {
          sid: '',
          equipment: [],
          debugHour: 0,
          quotaHour: 0
        }
      ]
      this.tempProcess.equipmentList[0].sid = 'b' + this.curEditIndex + '0'
    } else {
      this.tempProcess.equipmentList = []
    }
  }

  //选择双击设备
  changeMul(isSingle) {
    // console.log(tempProcess)
    if (isSingle) {
      // 单机
      this.maxEquitment = 1
    } else {
      // 双机
      this.maxEquitment = 2
    }
  }

  /**
   * 保存工艺路线
   */
  save() {
    if (this.validateSubmitProcessList()) {
      this.updateProcessRoute()
    }
  }
  async updateProcessRoute() {
    let result = await this.updata_VERSION({
      versionId: this.versionId,
      processList: this.requestList
    })
    if (result) {
      console.log('updateProcessRoute')
      this.$message.success('保存成功')
      this.canEdit = false
      this.preUpdate()
      this.copyRouteVisible = false
    }
  }

  async preUpdate() {
    // 修改不成功，重新获取原始数据
    let result = await this.GET_VERSION({ versionId: this.versionId })
    if (result) {
      this.processList = this.processDetailList[0].processList
      this.addSid()
    } else {
      console.log('修改工艺路线获取初始数据失败')
    }
  }

  close() {
    this.$router.go(-1)
    // // this.GET_PROCESS_DATEBASE({ ...this.sixSearch });
    // //初始化表格
    // this.processList = [
    //   {
    //     sid: 1,
    //     sequenceNumber: '1',
    //     processName: '',
    //     department: '',
    //     supplier: '',
    //     single: true,
    //     equipmentList: []
    //   }
    // ]
    // // this.over = true;
    // this.versionId = ''

    // //设备多选
    // this.maxEquitment = 1
    // //提交的表单数组
    // this.requestList = []
    // /*
    //  //整体外协
    // this.formDetail = {
    //   nn: false
    // }
    // */
    // //this.$refs.form.resetFields()
    // this.dialogVisible = false
    // this.$refs.form.resetFields()
    // this.initData()
  }

  //添加row-key
  addSid() {
    this.processList = this.processList.map((pItem, pIndex) => {
      pItem.sequenceNumber = pIndex + 1
      this.$set(pItem, 'sid', 'process' + pIndex)
      if (pItem.equipmentList) {
        pItem.equipmentList = pItem.equipmentList.map((eItem, eIndex) => {
          this.$set(eItem, 'sid', 'b' + pIndex + eIndex)
          return eItem
        })
      }
      return pItem
    })
  }

  //新增的 数据移到新数组
  changeData() {
    this.requestList = _.cloneDeep(this.processList)
    this.requestList = this.requestList.map((pItem, pIndex) => {
      delete pItem.sid
      delete pItem.sequenceId
      delete pItem.versionId
      return pItem
    })
  }

  //生产随机数
  random(lower, upper) {
    return Math.floor(Math.random() * (upper - lower)) + lower
  }
  //加工合并行
  merge({ row, column, rowIndex, columnIndex }) {
    //  console.log(row,row.equipment)

    if (!row.sequenceNumber) {
      if (columnIndex === 1) {
        return [1, 3]
      } else if (columnIndex === 2) {
        return [0, 0]
      } else if (columnIndex === 3) {
        return [0, 0]
      }
      //设置加号不展示
    }
  }

  delProcess(row) {
    this.$confirm(`是否移除工序 ${row.sequenceNumber}：${row.processName} ?`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
      .then(() => {
        this.processList.splice(row.sequenceNumber - 1, 1)
        this.addSid()
        this.isEditProcess = false
      })
      .catch(() => {})
  }

  get equitListLen() {
    return this.tempProcess.equipmentList.length
  }
  initData() {
    this.isEditProcess = false
    this.tempProcess = {
      sequenceNumber: 0,
      processName: '',
      department: '',
      single: false,
      equipmentList: []
    }
  }
  transformEquitToArr() {
    this.tempProcess.equipmentList = this.tempProcess.equipmentList.map(item => {
      item.equipment = item.equipment.split(',')
      return item
    })
  }
}
</script>

<style lang="scss">
.add-procee-pane {
  padding: 50px 50px 0 50px;
}

.addProcessDetail-dialog {
  .icon-xiugai1:before {
    font-size: 12px;
  }
  .icon-shanchu1:before {
    font-size: 12px;
  }
  .el-switch__label.is-active > span {
    font-weight: bold;
    font-size: 18px;
  }
}

.route-table {
  text-align: center;
  th {
    padding: 0 !important;
    height: 50px;
    line-height: 50px;
  }
  td {
    padding: 0 !important;
    height: 50px;
    line-height: 50px;
  }
}

// .el-table .row-outsource-process {
//   background-color: tan;
// }
// .el-table .row-finish-process {
//   background-color: turquoise;
// }
// .el-table .row-nohour-process {
//   background-color: violet;
// }
// .el-table .row-work-process {
//   background-color: yellow;
// }
</style>
